package com.wollo.service.impl;

import com.wollo.domain.User;
import com.wollo.mapper.PermissionMapper;
import com.wollo.mapper.RoleMapper;
import com.wollo.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private PermissionMapper permissionMapper;
    //TODO 用户登录业务逻辑
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //TODO 查询用户信息
        User user = userMapper.selectUserInfoByUserNameMapper(username);
        if (user == null) {
            throw new UsernameNotFoundException(username);
        }
        //TODO 创建集合存储权限信息
        List<SimpleGrantedAuthority> authorities = new ArrayList<>();
        //TODO 查询用户的权限和角色信息
        List<String> roles = roleMapper.selectRolesByUserIdMapper(user.getUid());
        for (String role : roles) {
            authorities.add(new SimpleGrantedAuthority("ROLE_"+role));
        }
        List<String> permissions = permissionMapper.selectPermissionByUserId(user.getUid());
        for (String permission : permissions) {
            authorities.add(new SimpleGrantedAuthority(permission));
        }
        return new org.springframework.security.core.userdetails.User(username,user.getPwd(),authorities);
    }
}
